package com.situ.service;

import com.situ.dao.UserDao;
import com.situ.dao.UserRoleDao;
import com.situ.entity.User;
import com.situ.vo.SexVO;
import com.situ.vo.TableVO;

import javax.servlet.http.HttpSession;
import java.util.List;

public class UserService {

    UserDao dao = new UserDao();
    UserRoleDao urDao = new UserRoleDao();

    public TableVO select(Integer page, Integer limit, String username, String tel) {
        TableVO vo = new TableVO();
        vo.setCount(dao.count(username, tel));
        vo.setData(dao.select(page, limit, username, tel));
        return vo;
    }

    public void delete(String id) {
        for (String s : id.split(",")) {
            dao.delete(Integer.parseInt(s));
        }
    }

    public void save(User u) {
        if (u.getId() == null) {
            dao.insert(u);
        } else {
            dao.update(u);
        }
    }

    public User info(Integer uid) {
        List<User> list = dao.info(uid);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    public boolean check(String username, String password, HttpSession session) {
        //1. 根据用户名查用户
        List<User> list = dao.selectByUsername(username);
        //2. 判断查到没有
        if (list.isEmpty()) {
            return false;
        }
        //3. 如果有，比较密码
        User u = list.get(0);
        boolean b = u.getPassword().equals(password);//TODO 暂时不考虑加密问题

        //4.如果密码正确：把当前用户保存进session
        if (b) {
            session.setAttribute("current", u);
        }
        //5.返回结果
        return b;
    }

    public void role(String type, Integer uid, Integer rid) {
        if ("add".equals(type)) {
            urDao.insert(uid, rid);
        } else {
            urDao.delete(uid, rid);
        }
    }

    public List<SexVO> stat() {
        return dao.stat();
    }
}
